package zekezang.org;

import common.utils.activity.ActivityQueue;
import common.utils.activity.ActivityUtils;
import common.utils.database.DatabaseHelper;
import common.utils.properties.SharedPreferencesUtils;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class WebviewActivity extends Activity {

	private WebView webView = null;
	private RelativeLayout menuLayout = null;
	private Button myButton = null;

	private LinearLayout mySearchView = null;

	private ProgressBar progressBar = null;
	private Handler handler = null;
	private Message message = null;

	private Animation animationOut = null;
	private Animation animationOut_s = null;
	private Animation animationIn = null;
	private Animation animationIn_s = null;

	private common.utils.activity.MainMenu mainMenu = null;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Window window = getWindow();
		window.requestFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.main);

		ActivityQueue.activityList.add(this);

		webView = (WebView) findViewById(R.id.myWebView);

		menuLayout = (RelativeLayout) findViewById(R.id.menu_layout);
		menuLayout.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				return true;
			}
		});

		mySearchView = (LinearLayout) findViewById(R.id.mySearchView);
		mySearchView.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				return true;
			}
		});

		myButton = (Button) findViewById(R.id.myButton);
		// myButton.setFocusable(true);
		// myButton.setFocusableInTouchMode(true);
		// myButton.requestFocus();

		myButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				menuShow();
			}
		});

		initSearch();
		processProgressBar();// 初始化looper
		init();// 执行初始化函数
		footerSetting();
	}

	@Override
	protected void onResume() {
		super.onResume();
		
		//判断全屏
		if(SharedPreferencesUtils.compare(this, "full_screen", "yes")){
			menuShow();
		}
		
		Intent intent = getIntent();
		String uri = intent.getStringExtra("uri");
		if (null != uri) {
			loadurl(webView, uri);
		} else {
			loadurl(webView, ActivityQueue.lastUri);
		}
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {// 捕捉返回键
		// mainMenu.responseOnKeyDown(keyCode, event);
		if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
			webView.goBack();
			webView.freeMemory();
			return true;
		} else if (keyCode == KeyEvent.KEYCODE_BACK && !webView.canGoBack()) {
			mainMenu.responseOnKeyDown(keyCode, event);
			ActivityUtils.getInstance().back_leftOUT_rightIN_Transition(WebviewActivity.this, getApplicationContext());
			return true;
		} else if (keyCode == KeyEvent.KEYCODE_MENU) {
			if (!myButton.isShown()) {
				hideSearchAndMenu();
			} else {
				menuShow();
			}
			return true;
		}
		return true;
	}

	private void menuShow() {
		// -----------menu show-----
		animationOut = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 1.0f,
				Animation.RELATIVE_TO_SELF, 0.0f);
		animationOut.setInterpolator(new AccelerateDecelerateInterpolator());
		animationOut.setDuration(1000);

		// -----------search show-----
		animationOut_s = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
				-1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
		animationOut_s.setInterpolator(new AccelerateDecelerateInterpolator());
		animationOut_s.setDuration(1000);

		// -----------menu hide-----
		animationIn = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
				Animation.RELATIVE_TO_SELF, 1.0f);
		animationIn.setInterpolator(new AccelerateDecelerateInterpolator());
		animationIn.setDuration(600);
		if (!menuLayout.isShown()) {
			menuLayout.setAnimation(animationOut);
			menuLayout.setVisibility(View.VISIBLE);
		}
		if (!mySearchView.isShown()) {
			mySearchView.setAnimation(animationOut_s);
			mySearchView.setVisibility(View.VISIBLE);
		}
		myButton.setAnimation(animationIn);
		myButton.setVisibility(View.GONE);
	}

	private EditText search_edit_text = null;
	private Button search_button_through = null;
	private Button search_button_search = null;
	private String regex = "(http://|https://)?([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?";

	private void initSearch() {
		search_edit_text = (EditText) findViewById(R.id.search_edit_text);
		search_edit_text.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			@Override
			public void onFocusChange(View view, boolean b) {
				if (b) {
					if (getResources().getString(R.string.edit_text).equals(search_edit_text.getText().toString().trim())) {
						search_edit_text.setText("");
					}
				}
			}
		});

		search_button_through = (Button) findViewById(R.id.search_button_through);
		search_button_search = (Button) findViewById(R.id.search_button_search);

		search_button_through.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				String uri = search_edit_text.getText().toString().trim();
				if (uri.matches(regex) && uri.length() > 0) {
					if (!uri.startsWith("http")) {
						uri = "http://" + uri;
					}
					ActivityUtils.getInstance().leftIN_rightOUT_Transition(WebviewActivity.this, getApplicationContext(), WebviewActivity.class,
							"uri", uri);
				} else {
					if (uri.length() > 0 && !getResources().getString(R.string.edit_text).equals(uri)) {
						String url = "http://web.roboo.com/direct.rob?query=" + uri + "&direct=直达";
						ActivityUtils.getInstance().leftIN_rightOUT_Transition(WebviewActivity.this, getApplicationContext(), WebviewActivity.class,
								"uri", url);
					} else {
						Toast.makeText(WebviewActivity.this, R.string.no_uri, Toast.LENGTH_SHORT).show();
					}
				}
			}
		});
		// search_button_search.setFocusable(true);
		// search_button_search.setFocusableInTouchMode(true);
		// search_button_search.requestFocus();
		search_button_search.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				String searchText = search_edit_text.getText().toString().trim();
				if (searchText.length() > 0 && !getResources().getString(R.string.edit_text).equals(searchText)) {
					String uri = "http://web.roboo.com/direct.rob?query=" + searchText + "&direct=搜索";
					ActivityUtils.getInstance().leftIN_rightOUT_Transition(WebviewActivity.this, getApplicationContext(), WebviewActivity.class,
							"uri", uri);
				} else {
					Toast.makeText(WebviewActivity.this, R.string.no_uri, Toast.LENGTH_SHORT).show();
				}
			}
		});
	}

	private void footerSetting() {
		mainMenu = common.utils.activity.MainMenu.getInstance(this, this, menuLayout, webView, "12345678", handler);
		// menu向上键
		ImageButton menu_up_button = (ImageButton) menuLayout.findViewById(R.id.menu_up_button);
		menu_up_button.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				mainMenu.responseOnKeyDown();
			}
		});
		// menu主页
		final ImageButton menu_home_button = (ImageButton) menuLayout.findViewById(R.id.menu_home_button);
		menu_home_button.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				mainMenu.responseOnTouch();
				ActivityUtils.getInstance().to_home_Transition(WebviewActivity.this, getApplicationContext(), MainActivity.class);
			}
		});
		// menu后退
		final ImageButton menu_back_button = (ImageButton) menuLayout.findViewById(R.id.menu_back_button);
		menu_back_button.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (webView.canGoBack()) {
					webView.goBack();
					webView.freeMemory();
				} else {
					mainMenu.responseOnTouch();
					ActivityUtils.getInstance().back_leftOUT_rightIN_Transition(WebviewActivity.this, getApplicationContext());
				}
			}
		});
		// menu前进
		final ImageButton menu_go_button = (ImageButton) menuLayout.findViewById(R.id.menu_go_button);
		menu_go_button.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (webView.canGoForward()) {
					webView.goForward();
					webView.freeMemory();
				} else {
					mainMenu.responseOnTouch();
					ActivityUtils.getInstance().forward_leftOUT_rightIN_Transition(WebviewActivity.this, getApplicationContext());
				}
			}
		});
	}

	private void processProgressBar() {
		handler = new Handler(Looper.myLooper()) {
			public void handleMessage(Message msg) {// 定义一个Handler，用于处理下载线程与UI间通讯
				if (!Thread.currentThread().isInterrupted()) {
					switch (msg.what) {
					case 0:
						progressBar.setVisibility(View.VISIBLE);// 显示进度对话框
						break;
					case 1:
						progressBar.setVisibility(View.GONE);// 隐藏进度对话框，不可使用dismiss()、cancel(),否则再次调用show()时，显示的对话框小圆圈不会动。
						break;
					case 2:
						progressBar.setProgress(msg.arg1);
						break;
					case 3:
						mainMenu.responseOnTouch();
						hideSearchAndMenu();
						progressBar.setVisibility(View.VISIBLE);
						break;
					}
				}
				super.handleMessage(msg);
			}
		};
	}

	private void init() {// 初始化

		progressBar = (ProgressBar) findViewById(R.id.myProgressBar);

		webView.setClickable(true);
		webView.getSettings().setJavaScriptEnabled(true);// 可用JS

		// Enum for specifying the WebView's desired density. FAR makes 100%
		// looking like in 240dpi MEDIUM makes 100% looking like in 160dpi CLOSE
		// makes 100% looking like in 120dpi
//		webView.getSettings().setDefaultZoom(ZoomDensity.FAR);
		webView.getSettings().setSupportZoom(true);
		// webView.getSettings().setBuiltInZoomControls(true);

		webView.setScrollBarStyle(0);// 滚动条风格，为0就是不给滚动条留空间，滚动条覆盖在网页上
		webView.setWebViewClient(new WebViewClient() {
			public boolean shouldOverrideUrlLoading(final WebView view, final String url) {
				// loadurl(view, url);// 载入网页
				Message message = new Message();
				message.obj = url;
				reloadHandler.sendMessage(message);
				view.freeMemory();
				return true;
			}// 重写点击动作,用webview载入

			// @Override
			// public void onReceivedSslError(WebView view, SslErrorHandler
			// handler, SslError error) {
			// super.onReceivedSslError(view, handler, error);
			// handler.proceed();
			// }
		});
		webView.setWebChromeClient(new WebChromeClient() {
			public void onProgressChanged(WebView view, int progress) {// 载入进度改变而触发
				ActivityQueue.lastUri = view.getUrl();
				if (progress >= 100) {
					handler.sendEmptyMessage(1);// 如果全部载入,隐藏进度对话框
					recordHistory(webView.getTitle(), webView.getUrl());// 记录历史
				} else {
					message = new Message();
					message.what = 2;
					message.arg1 = progress;
					handler.sendMessage(message);
				}
				super.onProgressChanged(view, progress);
			}
		});
		webView.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				mainMenu.responseOnTouch();
				hideSearchAndMenu();
				zoomControls(webView, arg1);
				return false;
			}
		});

	}

	private float OldX1 = 0.0f;
	private float OldY1 = 0.0f;
	private float OldX2 = 0.0f;
	private float OldY2 = 0.0f;
	private float NewX1 = 0.0f;
	private float NewY1 = 0.0f;
	private float NewX2 = 0.0f;
	private float NewY2 = 0.0f;

	private void zoomControls(WebView webView, MotionEvent event) {
		switch (event.getAction()) {
		case MotionEvent.ACTION_POINTER_2_DOWN:
			if (event.getPointerCount() == 2) {
				for (int i = 0; i < event.getPointerCount(); i++) {
					if (i == 0) {
						OldX1 = event.getX(i);
						OldY1 = event.getY(i);
					} else if (i == 1) {
						OldX2 = event.getX(i);
						OldY2 = event.getY(i);
					}
				}
			}
			break;
		case MotionEvent.ACTION_MOVE:
			if (event.getPointerCount() == 2) {
				for (int i = 0; i < event.getPointerCount(); i++) {
					if (i == 0) {
						NewX1 = event.getX(i);
						NewY1 = event.getY(i);
					} else if (i == 1) {
						NewX2 = event.getX(i);
						NewY2 = event.getY(i);
					}
				}
				float disOld = (float) Math.sqrt((Math.pow(OldX2 - OldX1, 2) + Math.pow(OldY2 - OldY1, 2)));
				float disNew = (float) Math.sqrt((Math.pow(NewX2 - NewX1, 2) + Math.pow(NewY2 - NewY1, 2)));
				if (disOld - disNew >= 25) {
					// 缩小
					webView.zoomOut();

				} else if (disNew - disOld >= 25) {
					// 放大
					webView.zoomIn();
				}
				OldX1 = NewX1;
				OldX2 = NewX2;
				OldY1 = NewY1;
				OldY2 = NewY2;
			}
		}
	}

	public void hideSearchAndMenu() {
		
		if(!SharedPreferencesUtils.compare(this, "full_screen", "yes")){
			if (menuLayout.isShown()) {
				// -----------menu show-----
				animationOut = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
						1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
				animationOut.setInterpolator(new AccelerateDecelerateInterpolator());
				animationOut.setDuration(1000);

				myButton.setAnimation(animationOut);
				myButton.setVisibility(View.VISIBLE);
			}

			if (menuLayout.isShown()) {
				// -----------menu hide-----
				animationIn = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
						0.0f, Animation.RELATIVE_TO_SELF, 1.0f);
				animationIn.setInterpolator(new AccelerateDecelerateInterpolator());
				animationIn.setDuration(600);

				menuLayout.setAnimation(animationIn);
				menuLayout.setVisibility(View.GONE);
			}
			if (mySearchView.isShown()) {
				// -----------search hide-----
				animationIn_s = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
						0.0f, Animation.RELATIVE_TO_SELF, -1.0f);
				animationIn_s.setInterpolator(new AccelerateDecelerateInterpolator());
				animationIn_s.setDuration(600);

				mySearchView.setAnimation(animationIn_s);
				mySearchView.setVisibility(View.GONE);
			}
		}
		
	}

	public void loadurl(final WebView view, final String url) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				handler.sendEmptyMessage(0);
				view.loadUrl(url);// 载入网页
			}
		}).start();
	}

	private Handler reloadHandler = new Handler(Looper.myLooper()) {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			handler.sendEmptyMessage(0);
			// webView.loadUrl(msg.obj.toString());// 载入网页
			String url = msg.obj.toString();
			if (url.indexOf("wtai://wp/mc;") != -1) {
				String phone = url.replace("wtai://wp/mc;", "");
				call(phone);
			} else {
				webView.loadUrl(url);// 载入网页
			}
		}
	};

	/**
	 * 拨打电话
	 */
	private void call(final String phone) {
		handler.post(new Runnable() {
			@Override
			public void run() {
				startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone)));
			}
		});
	}

	private SQLiteDatabase sqLiteDatabase = null;

	public void recordHistory(String description, String uri) {
		if (null != description && !description.equals("") && null != uri && !uri.equals("")) {
			sqLiteDatabase = new DatabaseHelper(this, "book_DB").getReadableDatabase();
			Cursor cursor = sqLiteDatabase.rawQuery("select count(id) as ids from book_history", new String[] {});
			Integer sign = 0;
			while (cursor.moveToNext()) {
				sign = cursor.getInt(cursor.getColumnIndex("ids"));
			}
			cursor.close();
			sqLiteDatabase.close();

			sqLiteDatabase = new DatabaseHelper(this, "book_DB").getWritableDatabase();
			sqLiteDatabase.beginTransaction();
			if (sign >= 30) {
				String sql = "delete from book_history where id in (select id from book_history limit 2)";
				sqLiteDatabase.execSQL(sql);
			}
			try {

				sqLiteDatabase.execSQL("insert into book_history (uriDescription,uri) values (?, ?)", new Object[] { description, uri });
				sqLiteDatabase.setTransactionSuccessful();
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				sqLiteDatabase.endTransaction();
				sqLiteDatabase.close();
			}
		}
	}
}